<#assign basePath=request.contextPath />
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户列表</title>
    <meta name="keywords" content="">
    <meta name="description" content="">

    <#include '/common/common-css.html'>
	<!-- ztree -->
	<link rel="stylesheet" href="${basePath}/js/plugins/zTree/css/zTreeStyle/myZTreeStyle.css" type="text/css">
</head>

<body class="gray-bg">
    <div class="wrapper wrapper-content animated fadeInRight">
        <div class="row">
            <div class="col-sm-12">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>用户 <small> 列表</small></h5>
                        <div class="ibox-tools">
                            <a class="collapse-link">
                                <i class="fa fa-chevron-up"></i>
                            </a>
                            <a href="javascript: location.replace(location.href);">
                                <i class="fa fa-refresh"></i>
                            </a>
                            <a class="close-link">
                                <i class="fa fa-times"></i>
                            </a>
                        </div>
                    </div>
                    <div class="ibox-content">
                    	<div class="row">
                    		<div class="col-md-2 b-r" style="height:400px">
                    			<div class="row">
                    				<div class="col-md-1 col-md-offset-10">
                    					<i class="fa fa-refresh" id="refreshTree"></i>
                    				</div>
                    			</div>
                    			<div class="row">
                    				<ul id="tree" class="ztree"></ul>
                    			</div>
                    		</div>
                    		<div class="col-md-10">
                    			<div class="row"  style="margin-bottom: 20px">
		                    		<div class="col-md-4 col-md-offset-4">
			                    		<div class="input-group">
							                <input type="text" name="name" id="name" class="form-control"> <span class="input-group-btn"> <button type="button" id="search" class="btn btn-primary">搜索用户
							                </button></span>
							            </div>
			                    	</div>
		                    	</div>
                    			<div class="col-md-12">
		                    		<div class="btn-group" style="margin-bottom: 6px;">
		                    			<@shiro.hasPermission name="user:add">
				                           	<button class="btn btn-primary btn-sm" type="button" id="add"><span class="glyphicon glyphicon-plus"></span> 添加</button>
		                    			</@shiro.hasPermission>
		                    			<@shiro.hasPermission name="user:delete">
				                            <button class="btn btn-danger btn-sm" type="button" id="batchDel"><span class="glyphicon glyphicon-trash"></span> 删除</button>
		                    			</@shiro.hasPermission>
		                    			<button class="btn btn-info btn-sm" type="button" id="refresh"><span class="fa fa-refresh"></span> 刷新</button>
			                        </div>
		                    	</div>
		                        <table id="myTab" class="table table-striped table-bordered table-hover dataTables-example" >
		                            <thead>
		                                <tr>
											<th><input type="checkbox"></th>
											<th>ID</th>
											<th>用户名</th>
											<th>真实姓名</th>
											<th>创建时间</th>
											<th>是否锁定</th>
											<th>操作</th>
		                                </tr>
		                            </thead>
		                            <tbody>
		                            </tbody>
		                        </table>
                    		</div>
                    	</div>
                    	
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 弹出层  -->
    <div id="modal-form" class="modal fade" aria-hidden="true">
        <div class="modal-dialog" style="width : 300px;">
            <div class="modal-content">
                <div class="modal-body">
                	<input type="hidden" id="userId">
                    <ul id="roleTree" class="ztree"></ul>
					<div class="pull-right">
						<button class="btn btn-sm btn-primary" id="roleBtn">确定</button>
					</div>
					<div class="clearfix"></div>
                </div>
            </div>
        </div>
    </div>
    
    <#include '/common/common-js.html'>
    <!-- ztree -->
    <script type="text/javascript" src="${basePath}/js/plugins/zTree/js/jquery.ztree.all.min.js"></script>
    <script type="text/javascript">
    var zTree;
    var roleTree;
	var setting = {
		view: {
			showIcon: false,
			nameIsHTML: true,
			//不允许多选
			selectedMulti: false
		},
		async: {
			enable: true,
			url: "${basePath}/org/tree?t=" + Math.random(),
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onClick: onClick,
			onRightClick: OnRightClick,
			onAsyncSuccess: zTreeOnAsyncSuccess
		}
	};
	
	var roleTree_setting = {
		view: {
			showIcon: false,
			nameIsHTML: true
		},
		check: {
			chkboxType:{"Y":"ps","N":"ps"},//勾选checkbox对于父子节点的关联关系  
		    chkStyle:"checkbox",
			enable: true
		},
		async: {
			enable: true,
			url: "${basePath}/role/tree?t=" + Math.random(),
		},
		data: {
			simpleData: {
				enable: true
			}
		},
		callback: {
			onAsyncSuccess: roleTreeOnAsyncSuccess
		}
	};
    
    $(function(){
    	//禁用浏览器右键菜单
		document.body.oncontextmenu = function(){
            return false;
        }
		
		$.fn.zTree.init($("#tree"), setting, null);
		$.fn.zTree.init($("#roleTree"), roleTree_setting, null);
    	
    	table = $('#myTab').DataTable({
    		//开启服务器模式
    		"serverSide" : true,
    		//关闭搜索
    		"searching" : false,
    		ajax: {
    	        "url": '${basePath}/user/list',
    	        "type" : "POST",
            	"data": function(d) {
					d.pageNum = d.start / d.length; //firstResult
					d.pageSize = d.length; //maxResult
					d.property = d.columns[d.order[0]["column"]].data; //排序字段
					d.direction = d.order[0]["dir"]; //升序降序
					d.name = $("#name").val();
            	},
    	    },
    	    "autoWidth": true,
    	    //设置行号
    	    /* "rowCallback": function (row, data, dataIndex) {
                $('td:eq(1)', row).html(dataIndex + table.page.info().length * table.page() + 1);
            }, */
    	    "order": [[ 1, 'asc' ]], //为了解决第一列checkbox小箭头问题
    	    "columnDefs": [
           		{
                    "defaultContent": "",
                  	"targets": "_all"
                },
                {
   					orderable:false,//禁用排序
   					targets:[0]   //指定的列
   			 	},
   				{ 
   			 		//为列设置样式
   			 		className: "text-center", 
   			 		"targets": [0]
   				}
            ],	   
    	    columns: [ 
    	    	{
            	    "data": "id",
                    render: function(data) {
                        return '<input type="checkbox" value="'+ data +'" name="">';
                    }
                },
    			{	"data" : "id"	},
    			{	"data" : "username"	},
    			{	"data" : "realname"	},
    			{
    				"data" : "createTime",
    				render: function(data) {
	                    return (new Date(data)).Format("yyyy-MM-dd hh:mm:ss");
                    }			
    			},
    			{
    				"data" : "locked",
    				render : function(data, type, row, meta){
    					if('0' == data){
    						return '<button type="button" class="btn btn-info btn-xs" onclick="lock(this, '+ row.id +', '+ data +')"><i class="fa fa-unlock"></i> 已启用</button>';
    					}else{
    						return '<button type="button" class="btn btn-warning btn-xs"  onclick="lock(this, '+ row.id +', '+ data +')"><i class="fa fa-lock"> 已锁定</button>';
    					}
    				}
    			},
    			{
    				"data" : "id",
    				render : function(data, row){
    					return '<@shiro.hasPermission name="user:edit"><button type="button" class="btn btn-success btn-xs" onclick="edit('+ data +')"><i class="fa fa-edit"></i> 修改</button></@shiro.hasPermission>' + 
                        '<span style="margin-right: 5px"></span>'+ 
                        '<a href="#modal-form"  data-toggle="modal" class="btn btn-warning  btn-xs" onclick="selectRole('+ data +')"><i class="fa fa-users"></i> 角色</a>'
    				}
    			}
    	    ]
    	});
    	
    	$("#refresh").on("click", function(){
    		table.ajax.reload();
    	});
    	
    	$("#search").on("click", function(){
    		table.ajax.reload();
    	});
    	
    	
    	$("#add").on("click", function(){
    		var org = zTree.getSelectedNodes()[0];
    		var orgName = org.name;
    		orgName = orgName.substring(orgName.lastIndexOf('>') + 2);
    		
    		layer.open({
    			type: 2,
    			area: ["60%", "80%"],
    			fix: false, //不固定
    			shadeClose: true, //是否点击遮罩关闭
    			maxmin: true,
    			title: "添加用户",
    			content: "${basePath}/user/add?orgId=" + org.id + "&orgName=" + orgName
    		});
    	});
    	
    	
    	//批量删除
    	$("#batchDel").on("click", function(){
    		layer.confirm('确认要删除吗？',function(){
	    		var ids = new Array();
	    		$("tbody").find("input:checkbox:checked").each(function(){
	    			ids.push($(this).val());
	    		});
	    		
	    		if(ids.length > 0){
	    			$.ajax({
	    				type: 'POST',
	    				url: "${basePath}/user/batchDel",
	    				data: JSON.stringify(ids),
	    				contentType: "application/json; charset=utf-8",
	    				dataType: 'json',
	    				success: function(data){
	    					if(data.error){
	    						layer.msg(data.msg,{icon:2,time:1000});
	    					}else{
	    						if(data > 0){
			    					$("tbody").find("tr").each(function(){
			    						var id = $(this).find("td:eq(1)").text();
			    						if($.inArray(id, ids) > -1){
			    							$(this).find("td:eq(5)").html('<button type="button" class="btn btn-warning btn-xs" onclick="lock(this , '+ id +', 1)"><i class="fa fa-lock"> 已锁定</button>');
			    						}
			    					});
			    					$('input:checkbox').removeAttr('checked');
			    					layer.msg('批量删除成功!',{icon:1,time:1000});
		    					}
	    					}
	    				},
	    				error:function(e) {
	    					console.log(e);
	    				}
	    			});
	    		}else{
	    			layer.alert("请选择要删除的用户");
	    		}
    		});
    	});
    	
    	/* 刷新树 */
    	$("#refreshTree").on("click", function(){
    		zTree.reAsyncChildNodes(null, "refresh");
    	});
    	
    	/* 选择权限 */
    	$("#roleBtn").on("click", function(){
    		var userId = $("#userId").val();
    		var nodes = roleTree.getCheckedNodes(true);
    		var ids = new Array();
    		ids.push(userId);
    		for(var i in nodes){
				ids.push(nodes[i].id);
			}
    		
    		$.ajax({
				type: 'POST',
				url: "${basePath}/user/associateRole",
				data: JSON.stringify(ids),
				contentType: "application/json; charset=utf-8",
				dataType: 'json',
				success: function(data){
					if(data.error){
						layer.msg(data.msg,{icon:2,time:1000});
					}else{
						if(data >= 1){
							layer.msg('关联成功!',{icon:1,time:1000});
							$('#modal-form').modal('hide');
						}
					}
				},
				error:function(e) {
					console.log(e);
				}
			});
    	});
    });
    
    /* 锁定用户 */
    function lock(obj, id, value){
    	value = "0" == value ? "1" : "0";
    	$.ajax({
			type: 'POST',
			url: '${basePath}/user/lock?t=' + Math.random(),
			data : {
				"id" : id,
				"locked" : value
			},
			dataType: 'json',
			success: function(data){
				if(data.error){
					layer.msg(data.msg,{icon:2,time:1000});
				}else{
					if('1' == data){
						if('1' == value){
							$(obj).parent().html('<button type="button" class="btn btn-warning btn-xs"  onclick="lock(this , '+ id +', '+ value +')"><i class="fa fa-lock"> 已锁定</button>');
							layer.msg('锁定成功!',{icon:1,time:1000});
						}else{
							$(obj).parent().html('<button type="button" class="btn btn-info btn-xs"  onclick="lock(this, '+ id +', '+ value +')"><i class="fa fa-unlock"> 已启用</button>');
							layer.msg('启用成功!',{icon:1,time:1000});
						}
					}else{
						layer.msg('锁定失败',{icon:1,time:1000});
					}
				}
			},
			error:function(e) {
				console.log(e);
			}
		});		
    }
    
    /* 修改用户 */
    function edit(id){
    	layer.open({
			type: 2,
			area: ["60%", "80%"],
			fix: false, //不固定
			shadeClose: true, //是否点击遮罩关闭
			maxmin: true,
			title: "修改用户",
			content: "${basePath}/user/edit?id=" + id
		});
    }
    
    /* 删除用户 */
    function del(obj, id){
    	layer.confirm('确认要删除吗？',function(index){
    		$.ajax({
    			type: 'POST',
    			url: '${basePath}/user/delete?t=' + Math.random(),
    			data : {"id" : id},
    			dataType: 'json',
    			success: function(data){
    				if(data.error){
						layer.msg(data.msg,{icon:2,time:1000});
					}else{
						if(1 == data){
	    					$(obj).parents("tr").remove();
	    					layer.msg('已删除!',{icon:1,time:1000});
	    				}else{
	    					layer.msg('删除失败',{icon:1,time:1000});
	    				}
					}
    			},
    			error:function(e) {
    				console.log(e);
    			}
    		});		
    	});
    }
    
    /* 选择角色 */
    function selectRole(id){
    	console.log("当前用户id:" + id)
    	$("#userId").val(id);
    	roleTree.checkAllNodes(false);
    	
    	//根据用户id查询用户对应的权限
    	$.ajax({    
	        type: "post",   
	        url: "${ basePath }/user/roleIds?t=" + Math.random(),   
	        data : {
	        	id : id
	        },
	        dataType: "json",    
	        success: function (roleIds) {     
	        	if(roleIds.error){
					layer.msg(roleIds.msg,{icon:2,time:1000});
				}else{
					var nodes = roleTree.getNodes();
		        	$(roleIds).each(function(){
		        		roleTree.checkNode( roleTree.getNodeByParam("id", this), true);
		        	});
				}
	        },
	        error : function(e){
	        	console.log(e);
	        }
	    })
    }
    
    /* 单击树 */
    function onClick(event, treeId, treeNode, clickFlag) {
	}	
	
    /* 右键单击树 */
	function OnRightClick(event, treeId, treeNode) {
	}
	
    /* 角色树加载完成后回调 */
	function roleTreeOnAsyncSuccess(event, treeId, msg) {  
    	roleTree = $.fn.zTree.getZTreeObj("roleTree");
    	roleTree.expandAll(true);//全部展开  
	}
	
    /* 组织机构树加载完成后回调 */
	function zTreeOnAsyncSuccess(event, treeId, msg) {  
		zTree = $.fn.zTree.getZTreeObj("tree");
		zTree.expandAll(true);//全部展开  
		//默认选中根节点
		var nodes = zTree.getNodes();
		zTree.selectNode(nodes[0]);
	}
    </script>
</body>
</html>
